package lxs.swift.tool.http;

import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class FormPoster extends KVSender {
    private final String BOUNDARY = System.currentTimeMillis() + "";

    public FormPoster(Config config) {
        super(config, "", "", "");
        // 设置边界
        config.header("Content-Type", "multipart/form-data; boundary=" + this.BOUNDARY);
        super.open();
//        write("\r\n".getBytes(config.charset));
    }

    @Override
    public byte[] toBytes(String key, Object value) {
        if (key == null || key.isEmpty() || value == null) return new byte[0];
        // 请求正文信息
        String item = "\r\n--" + BOUNDARY +
                "\r\nContent-Disposition: form-data; name=\"" + key + "\"" +
                "\r\n" +
                "\r\n" + value;
        return item.getBytes(config.charset);
    }

    public FormPoster sendFile(String name, File file) {
        if (name == null || name.isEmpty() || file == null) return this;
        try (DataInputStream in = new DataInputStream(Files.newInputStream(file.toPath()));) {
            // 请求正文信息
            // 第一部分：
            String item = "\r\n--" + BOUNDARY +
                    "\r\nContent-Disposition: form-data; name=\"" + name + "\"; filename=\"" + file.getName() + "\"" +
                    "\r\nContent-Type: application/octet-stream" +
                    "\r\n" +
                    "\r\n";
            out.write(item.getBytes(config.charset));
            int bytes;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
        } catch (IOException e) {
            super.close();
            throw new RuntimeException(e);
        }
        return this;
    }


    public Receiver read() {
        write(("\r\n--" + BOUNDARY + "--\r\n").getBytes(config.charset));
        return super.read();
    }
}
